//
//  ExamLevelViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/2/7.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

enum ExamLevelSetType {
    case set
    case change
}

class ExamLevelViewController: TableViewController {

    var levels = [[String: Any]]()
    var selectLevelId: Int?
    
    var setType = ExamLevelSetType.change
    
    @IBOutlet weak var backBtn: UIButton!
    @IBOutlet weak var saveButtonItem: UIBarButtonItem!
    
    static func controller(_ setType:ExamLevelSetType = .change) -> ExamLevelViewController {
        let vc = ExamLevelViewController.viewController(storyboardName: "Mine") as! ExamLevelViewController
        vc.setType = setType
        return vc
    }
    
    @IBAction func backClick(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func saveClick(_ sender: UIBarButtonItem) {
        guard let levelId = selectLevelId else { return }
     
        if setType == .set {
            changeLevel(levelId: levelId)
        }
        else if setType == .change {
            lsf_alert("是否保存修改", viewController: self, cancelTitle: "取消", destructiveTitle: "保存", handle: { (title) in
                if title == "保存" {
                    self.changeLevel(levelId: levelId)
                }
            })
        }
    }
    
    func changeLevel(levelId: Int) {
        
        startAnimating()
        
        ExamLevel.levelSelect(levelId: levelId, success: { [weak self] (_, _) in
            stopAnimating()
            
            guard let strongSelf = self else { return }
            if strongSelf.setType == .set {
                // 发送通知：
                NotificationCenter.default.post(name: Notification.Name(rawValue: LoginViewControllerNotification), object: LoginType.rigist)
            }
                
                //改变试卷等级
            else {
                strongSelf.navigationController?.popViewController(animated: true)
            }
            }, failure: { (code, msg) in
                stopAnimating()
                lsf_alert(msg)
        })
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        

        if setType == .set {
            backBtn.isHidden = true
        }
        
        selectLevelId = AccountStorage.default.account.levelId
        loadData()
    }
    
    func loadData() {
        startAnimating()
        ExamLevel.levelList(success: { [weak self] (response, data) in
            stopAnimating()
            if let data = data as? [[String:Any]], let strongSelf = self {
                strongSelf.levels = data
                strongSelf.tableView.reloadData()
            }
        }) { (code, msg) in
            stopAnimating()
            lsf_alert(msg)
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return levels.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ExamLevelCell", for: indexPath) as! ExamLevelCell

        if indexPath.row < levels.count {
            let item = levels[indexPath.row]
            let title = item["name"] as? String
            
            var isSelect = false
            if let id = item["levelId"] as? Int {
                isSelect = (selectLevelId == id)// ? true : false
            }

            cell.set(title: title, isSelect: isSelect)
        }
        // Configure the cell...

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.row < levels.count {
            let item = levels[indexPath.row]
            self.selectLevelId = item["levelId"] as? Int
            tableView.reloadData()
        }
    }
}

class ExamLevelCell: UITableViewCell {
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var radioImageView: UIImageView!
    
    func set(title:String?, isSelect:Bool?) {
        titleLabel.text = title
        
        if isSelect == true {
            radioImageView.image = UIImage.init(named: "选中")
        }
        else {
            radioImageView.image = UIImage.init(named: "checked")
        }
    }
}




















